package com.my.article.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.my.article.mapper.ApArticleContentMapper;
import com.my.article.mapper.ApArticleMapper;
import com.my.article.service.ArticleFreemarkerService;
import com.my.common.constans.ArticleConstas;
import com.my.file.service.FileStorageService;
import com.my.model.article.pojos.ApArticle;
import com.my.model.article.pojos.ApArticleContent;
import com.my.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 异步生成静态页面到Minio
     * @param apArticle
     * @param apArticleContent
     */
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String apArticleContent) {
        StringWriter out = new StringWriter();
        if(StringUtils.isNotBlank(apArticleContent)){
            try {
                if(apArticle.getStaticUrl() != null) {
                    //删除原来Url
                    fileStorageService.delete(apArticle.getStaticUrl());
                    log.info("成功删除原来的html静态文件");
                }
                log.info("开始生成新的静态html文件...");
                //1.文章内容通过freemarker生成html文件
                Template template = configuration.getTemplate("article.ftl");

                Map<String, Object> params = new HashMap<>();
                params.put("content", JSONArray.parseArray(apArticleContent));

                template.process(params, out);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //2.把html文件上传到minio中
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);
            log.info("将html文件上传到minio中:{}",path);

            //3.修改ap_article表，保存static_url字段
            ApArticle article = new ApArticle();
            article.setId(apArticle.getId());
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);

            //4.创建索引，发送消息
            createArticleESIndex(article,apArticleContent,path);
        }
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 创建索引，发送消息
     * @param article
     * @param apArticleContent
     * @param path
     */
    private void createArticleESIndex(ApArticle article, String apArticleContent, String path) {
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticleContent,searchArticleVo);
        searchArticleVo.setContent(apArticleContent);
        searchArticleVo.setStaticUrl(path);

        //发送消息
        kafkaTemplate.send(ArticleConstas.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
    }
}
